<?php
/**
 * (logic)
 */
namespace App\Logic\MonthlyReportLT;

use App\Models\Basics\SysPlat;
use App\Models\MonthlyReportLT\Cost\LogisticsBalance;
use App\Models\OverSeasIn\Delivery as OSDelivery;
use Illuminate\Support\Facades\DB;
class CheckLogisticsBalance
{
    public static function exe()
    {
        try{
            DB::beginTransaction();
            self::_exePlacingOSDropShipping();
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 1.国内仓发往海外仓代发
     */
    private static function _exePlacingOSDropShipping(){
        $ds = OSDelivery::with('detail')
            ->where('plat_id',SysPlat::PLAT_RAKUTEN)
            ->where('delivery_type',OSDelivery::OS_DELIVERY_DROPSHIPPING)
            ->where('status','>=',6)//已发货或已入海外仓中转仓
            ->where('logistics_status',2)//运费已更新
            ->where('logistics_fee_status',0)//未纳入统计
            ->where('logistics_check_status',0)//运费核算状态正常
            ->orderBy('delivered_at','ASC')
            ->get();
        foreach ($ds as $d){
            foreach ($d->detail as $item){
                if($item->ship_num == 0)continue;
                $count = LogisticsBalance::query()
                    ->where('psku_id' , $item->psku_id)
                    ->where('delivery_no' , $d->delivery_no)
                    ->count();
                if($count > 0)continue;
                LogisticsBalance::query()->create(
                    [
                        'psku_id' => $item->psku_id,
                        'delivery_no' => $d->delivery_no,
                        'delivered_at' => $d->delivered_at,
                        'b_num' => $item->ship_num,
                        'b_price' => $item->logistics_fee ?: 0,
                        'b_balance_sale' => $item->ship_num,
                    ]
                );
            }
            $d->logistics_fee_status = 1;
            $d->save();
        }
    }
}
